﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Cesave.Domain.PermisosModule.Resources;
using Cesave.Domain.Core;
using System.Data;

namespace Cesave.Domain.PermisosModule.Contracts.Ejidos
{
	/// <summary>
	/// 
	/// </summary>
	public class EjidoService
		: IEjidoService
	{
		#region Private properties

		/// <summary>
		/// 
		/// </summary>
		private IEjidoRepository _ejidoRepository;

		#endregion

		#region Constructor

		/// <summary>
		/// 
		/// </summary>
		/// <param name="ejidoRepository"></param>
		public EjidoService(IEjidoRepository ejidoRepository)
		{
			if (ejidoRepository == null)
				throw new ArgumentNullException(Messages.exception_DependenciesAreNotInitialized, "ejidoRepository");
			_ejidoRepository = ejidoRepository;
		}

		#endregion

		#region IEjidoService Members

		/// <summary>
		/// 
		/// </summary>
		/// <param name="ejido"></param>
		public void AddEjido(Entities.Ejido ejido)
		{
			if (ejido == null)
				throw new ArgumentNullException(Messages.exception_InvalidArgument, "ejido");
			IUnitOfWork unitOfWork = _ejidoRepository.StoreContext;
			_ejidoRepository.Add(ejido);
			try
			{
				unitOfWork.Commit();
			}
			catch (OptimisticConcurrencyException)
			{
				unitOfWork.RollbackChanges();
				unitOfWork.CommitAndRefreshChanges();
			}
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="ejido"></param>
		public void ChangeEjido(Entities.Ejido ejido)
		{
			if (ejido == null)
				throw new ArgumentNullException(Messages.exception_InvalidArgument, "ejido");
			IUnitOfWork unitOfWork = _ejidoRepository.StoreContext;
			try
			{
				unitOfWork.Commit();
			}
			catch (OptimisticConcurrencyException)
			{
				unitOfWork.RollbackChanges();
				unitOfWork.CommitAndRefreshChanges();
			}
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="municipioGuid"></param>
		/// <returns></returns>
		public List<Entities.Ejido> FindEjidosByMunicipio(Guid municipioGuid)
		{
			if (municipioGuid == Guid.Empty)
				throw new ArgumentException(Messages.exception_InvalidArgument, "municipioGuid");
			EjidosByMunicipioSpecification specification = new EjidosByMunicipioSpecification(municipioGuid);
			return _ejidoRepository.FindEjidosByMunicipio(specification).ToList();
		}

		#endregion

		#region IDisposable Members

		public void Dispose()
		{
			if (_ejidoRepository != null && _ejidoRepository.StoreContext != null)
				_ejidoRepository.StoreContext.Dispose();
		}

		#endregion
	}
}
